<?php
/**
 * 绑定用户信息
 * [WeEngine System] Copyright (c) 2014 W7.CC.
 */
defined('IN_IA') or exit('Access Denied');
load()->model('user');

$dos = array('display', 'validate_mobile', 'bind_mobile', 'bind_oauth', 'console', 'verify_mobile', 'bind_console', 'console_url');
$do = in_array($do, $dos) ? $do : 'display';

if (in_array($do, array('validate_mobile', 'bind_mobile', 'verify_mobile'))) {
	$user_profile = table('users_profile')->getByUid($_W['uid']);
	$mobile = safe_gpc_string($_GPC['mobile'], '', 'mobile');
	if (empty($mobile)) {
		iajax(-1, '手机号不能为空');
	}
	if (!preg_match(REGULAR_MOBILE, $mobile)) {
		iajax(-1, '手机号格式不正确');
	}
	$bind_type = in_array($do, array('verify_mobile')) ? USER_REGISTER_TYPE_CONSOLE : USER_REGISTER_TYPE_MOBILE;
	$mobile_exists = table('users_bind')->getByTypeAndBindsign($bind_type, $mobile);
	if (empty($type) && !empty($mobile_exists)) {
		iajax(-1, '手机号已存在');
	}
}

if ('validate_mobile' == $do) {
	iajax(0, '本地校验成功');
}

if ('bind_mobile' == $do) {
	if ($_W['isajax'] && $_W['ispost']) {
		$bind_info = OAuth2Client::create('mobile')->bind();
		if (is_error($bind_info)) {
			iajax(-1, $bind_info['message']);
		}
		iajax(0, '绑定成功', url('user/profile/bind'));
	} else {
		iajax(-1, '非法请求');
	}
}

if ('display' == $do) {
	$support_bind_urls = user_support_urls();
	$setting_sms_sign = setting_load('site_sms_sign');
	$bind_sign = !empty($setting_sms_sign['site_sms_sign']['register']) ? $setting_sms_sign['site_sms_sign']['register'] : '';
	if (!empty($_W['user']['type']) && $_W['user']['type'] == USER_TYPE_CLERK) {
		$_W['setting']['copyright']['bind'] = empty($_W['setting']['copyright']['clerk']['bind']) ? '' : $_W['setting']['copyright']['clerk']['bind'];
	}
	if (empty($_W['isw7_request'])) {
		$_W['setting']['copyright']['bind'] = 'console';
	}
}

if ('bind_oauth' == $do) {
	$uid = intval($_GPC['uid']);
	$openid = safe_gpc_string($_GPC['openid']);
	$register_type = intval($_GPC['register_type']);

	if (empty($uid) || empty($openid) || !in_array($register_type, array(USER_REGISTER_TYPE_QQ, USER_REGISTER_TYPE_WECHAT))) {
		itoast('参数错误!', url('user/login'), '');
	}
	$user_info = user_single($uid);
	if ($user_info['is_bind']) {
		itoast('账号已绑定!', url('user/login'), '');
	}

	if ($_W['ispost']) {
		$member['username'] = safe_gpc_string($_GPC['username']);
		$member['password'] = safe_check_password($_GPC['password']);
		$member['repassword'] = safe_check_password($_GPC['repassword']);
		$member['is_bind'] = 1;

		if (empty($member['username']) || empty($member['password']) || empty($member['repassword'])) {
			itoast('请填写完整信息！', referer(), '');
		}
		if (!safe_gpc_string($member['username'])) {
			itoast('必须输入用户名，格式为 3-15 位字符，可以包括汉字、字母（不区分大小写）、数字、下划线和句点。', referer(), '');
		}
		if (user_check(array('username' => $member['username']))) {
			itoast('非常抱歉，此用户名已经被注册，你需要更换注册名称！', referer(), '');
		}
		if (is_error($member['password'])) {
			itoast($member['password']['message'], referer(), '');
		}
		if ($member['password'] != $member['repassword']) {
			itoast('两次秘密输入不一致');
		}
		unset($member['repassword']);
		if (user_check(array('username' => $member['username']))) {
			itoast('非常抱歉，此用户名已经被注册，你需要更换注册名称！', referer(), '');
		}

		$member['salt'] = random(8);
		$member['password'] = user_hash($member['password'], $member['salt']);
		$result = pdo_update('users', $member, array('uid' => $uid, 'openid' => $openid, 'register_type' => $register_type));
		if ($result) {
			itoast('注册绑定成功!', url('user/login'), '');
		} else {
			itoast('注册绑定失败, 请联系管理员解决!', url('user/login'), '');
		}
	} else {
		template('user/bind-oauth');
		exit;
	}
}

if ('console' == $do) {
	$code = safe_gpc_string($_GPC['code']);
	$token = cloud_oauth_token($code);
	if (empty($code) || is_error($token)) {
		$url = cloud_oauth_login_url($_W['setting']['site']['url'] . '/web/' . url('user/third-bind/console'));
		if (empty($url)) {
			message('授权用户登录失败，请联系管理员处理', 'https://console.w7.cc', 'error');
		}
		header('Location:' . $url);
		exit;
	}
	$cachekey = cache_system_key('cloud_bind_console_token', array('code' => $code));
	$cache = cache_load($cachekey);
	if (empty($cache)) {
		cache_write($cachekey, $token, $token['expire_time']);
	}
	template('user/console');
	exit();
}

if (in_array($do, array('verify_mobile'))) {
	if (!$_W['isajax']) {
		iajax(-1, '非法请求');
	}
}

if ('verify_mobile' == $do) {
	$code = safe_gpc_string($_GPC['code']);
	if (empty($code)) {
		iajax(-1, '请输入验证码');
	}
	$data = array(
		'mobile' => $mobile,
		'sms_verify_code' => $code
	);
	$result = cloud_check_mobile($data);
	if (is_error($result)) {
		iajax(-1, $result['message']);
	}
	if (!empty($result['out_user_id'])) {
		if ($_W['uid'] != $result['out_user_id']) {
			$user = pdo_get('users', array('uid' => $result['out_user_id']), array('username'));
			$message = '该手机号已绑定用户 ' . empty($user['username']) ? '' : $user['username'] . ' ，请更换其他手机号';
			iajax(-1, $message);
		}
	}
	iajax(0, $result);
}

if ('bind_console' == $do) {
	if (!empty($_GPC['username']) && !empty($_GPC['password'])) {
		$data = array(
			'username' => safe_gpc_string($_GPC['username']),
			'password' => safe_gpc_string($_GPC['password']),
		);
		pdo_delete('users_failed_login', array('lastupdate <' => TIMESTAMP - $_W['setting']['copyright']['refused_login_limit'] * 60));
		$failed = pdo_get('users_failed_login', array('username' => $data['username']));
		if ($failed['count'] >= 5) {
			iajax('-1', "输入密码错误次数超过5次，请在{$_W['setting']['copyright']['refused_login_limit']}分钟后再尝试。");
		}
		$user_check = user_check($data);
		if (!empty($user_check)) {
			if (!empty($failed)) {
				pdo_delete('users_failed_login', array('id' => $failed['id']));
			}
			$if_bind = pdo_get('users_bind', array('uid' => $user_check, 'third_type' => USER_REGISTER_TYPE_CONSOLE));
			if (!empty($if_bind)) {
				iajax(-1, '用户：' . $data['username'] . ' 已被绑定，请更换其他账号。');
			}
			$openid_if_bind = pdo_get('users_bind', array('bind_sign' => safe_gpc_string($_GPC['openid']), 'third_type' => USER_REGISTER_TYPE_CONSOLE));
			if (!empty($openid_if_bind)) {
				iajax(-1, '当前商城账号已绑定过该站点用户，不可违规操作！');
			}
			$_W['uid'] = $user_check;
		} else {
			if (empty($failed)) {
				pdo_insert('users_failed_login', array('ip' => $_W['clientip'], 'username' => $data['username'], 'count' => '1', 'lastupdate' => TIMESTAMP));
			} else {
				pdo_update('users_failed_login', array('count' => $failed['count'] + 1, 'lastupdate' => TIMESTAMP), array('id' => $failed['id']));
			}
			iajax(-1, '用户名密码不符，请检查您输入的账号和密码');
		}
	}
	$code = safe_gpc_string($_GPC['code']);
	if (empty($code)) {
		if ($_W['isajax']) {
			iajax(-1, '参数错误');
		}
		itoast('参数错误！', '', 'info');
	}
	$cachekey = cache_system_key('cloud_bind_console_token', array('code' => $code));
	$token = cache_load($cachekey);
	if (empty($token)) {
		if ($_W['isajax']) {
			iajax(-1, '参数错误');
		}
		itoast('参数错误', '', 'info');
	}
	$console_user = cloud_oauth_user($token['access_token']);
	if (is_error($console_user)) {
		if ($_W['isajax']) {
			iajax(-1, $console_user['message']);
		}
		itoast($console_user['message'], '', 'info');
	}
	$result = cloud_bind_user_token(array(
		'access_token' => $token['access_token'],
		'out_user_id' => $_W['uid'],
		'role_identify' => user_is_vice_founder() ? 'role2' : 'role1'
	));
	if (is_error($result)) {
		if ($_W['isajax']) {
			iajax(-1, $result['message']);
		}
		itoast($result['message'], '', 'info');
	}

	$user_bind = pdo_get('users_bind', array('uid' => $_W['uid'], 'third_type' => USER_REGISTER_TYPE_CONSOLE));
	if (empty($user_bind)) {
		pdo_insert('users_bind', array('uid' => $_W['uid'], 'bind_sign' => $console_user['openid'], 'third_nickname' => $console_user['username'], 'third_type' => USER_REGISTER_TYPE_CONSOLE));
	} else {
		pdo_update('users_bind', array('bind_sign' => $console_user['openid'], 'third_nickname' => $console_user['username']), array('id' => $user_bind['id']));
	}
	if ($_W['isajax']) {
		iajax(0, '绑定成功', $_W['siteroot'] . 'web/home.php');
	}
	header("Location: " . url('user/third-bind/console_url', array('type' => 'client')));
}

if ('console_url' == $do) {
	$type = safe_gpc_string($_GPC['type']);
	if (empty($type) || !in_array($type, array('we7', 'client', 'system'))) {
		itoast('参数错误！');
	}
	if ('system' == $type) {
		$type = 'we7';
	}
	$data = [
		'out_user_id' => empty($_W['isadmin']) ? $_W['uid'] : 0,
		'console_type' => $type
	];
	if (!empty($_GPC['out_user_id'])) {
		$data['out_user_id'] = safe_gpc_int($_GPC['out_user_id']);
	}
	$result = cloud_console_index_url($data);
	if (is_error($result)) {
		itoast($result['message']);
	}
	$url = $result['data'];
	header('location: ' . $url);
	exit();
}
template('user/third-bind');
